function rankPageOnNextPageClick(target) {
    var currentPage = $(target).attr('curpage');
    if (currentPage.trim() == '') return;
    currentPage = parseInt(currentPage);
    var pathName = window.location.pathname;
    var array = pathName.split('/');
    var lastPart = array[array.length - 1];
    if (parseInt(lastPart) == currentPage) {
        var path = '';
        currentPage += 1;
        for (var i = 0; i < array.length - 1; ++i) {
            path += array[i];
            path += '/';
        }
        path += currentPage;

        window.location.href = path;
    }
}

function rankPageOnPreviousPageClick(target) {
    var currentPage = $(target).attr('curpage');
    if (currentPage.trim() == '') return;
    currentPage = parseInt(currentPage);
    var pathName = window.location.pathname;
    var array = pathName.split('/');
    var lastPart = array[array.length - 1];
    if (parseInt(lastPart) == currentPage) {
        var path = '';
        currentPage -= 1;
        for (var i = 0; i < array.length - 1; ++i) {
            path += array[i];
            path += '/';
        }
        path += currentPage;

        window.location.href = path;
    }
}

function rankPageOnCatlogClick(target) {
    console.log(target  + " is ");
    var handle = target.children[0];

    if (handle.innerText) {
        $.ajax({
            type: 'post',
            async: true,
            data: {'rootcatlog': handle.innerText},
            url: document.location.origin + '/api/getcatlogs',
            dataType: 'text',
            error: function() {

            },
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {

                }
                else {
                    console.log(json.description);
                }
            }
        });
    }
    else {
        console.log("catlog name strange, are you sure?");
    }
}

function rankPageCollectToggle(target, open) {
    if (open) {
        $(target).removeClass("collect-disable");
        $(target).addClass("collect-enable");
    }
    else {
        $(target).removeClass("collect-enable");
        $(target).addClass("collect-disable");
    }
}

function rankPageOnCollectClick(target) {
    var token = getCookie("token");
    if (token == null || token == '') {
        showDialogToAskLogin('收藏');
        event.stopPropagation();
        return;
    }

    var fictionId = target.parentNode.parentNode.getAttribute("fictionid");

    $.ajax({
        type: 'post',
        async: true,
        data: {"id": fictionId},
        url: document.location.origin + '/api/collect',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                var collectOrNot = json.collect;

                if (collectOrNot == true) {
                    rankPageCollectToggle(target, true);
                }
                else {
                    rankPageCollectToggle(target, false);
                }
            }
            else {
                console.log(json.description);
            }
        }
    });

    event.stopPropagation();
}

function rankPageOnFictionClick(target) {
    var id = target.getAttribute("fictionid");
    window.location.href = document.location.origin + "/fiction/" + URLencode(id);
}

/**
 * Document ready
 */
$(document).ready(function () {

    $("#fictionTable").DataTable({
        "paging": false,         //是否分页，如果是false，则全部显示，否则默认是10个数据一页
        "lengthChange": false,   //是否可以控制每页多少个数据，这个会影响Show x entries的显示
        "searching": false,      //是否要显示search栏
        "ordering": false,       //是否出排序的小控件
        "info": false,           //表格的左下方是否需要显示Showing # to # of # entries
        "autoWidth": true,       //
        "language": {
            "lengthMenu": "每页显示记录 _MENU_",
            "zeroRecords": "没有任何内容",
            "info": "当前第_PAGE_页，共_PAGES_页",
            "infoEmpty": "No records available",
            "infoFiltered": "(filtered from _MAX_ total records)",
            "search": "搜索：",
            "paginate": {
                "first":      "首頁",
                "last":       "末頁",
                "next":       "下一頁",
                "previous":   "前一頁"
            },
        },
    });

    $.ajax(
        {
            type: 'post',
            async: true,
            data: '',
            url: document.location.origin + '/api/getrootcatlog',
            dataType: 'text',
            error: function () {
                console.log("Ajax 发生错误！");
            },
            success: function (data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                    var totalCount = json.data.length;
                    var totalRow = Math.ceil(totalCount / 4);

                    var tableHandle = $('#rootcatlog-table');

                    var curIndex = 0;
                    for (var row = 0; row < totalRow; ++row) {
                        var rowHandle = tableHandle.append('<tr></tr>');
                        for (var col = 0; col < 4; ++col) {
                            rowHandle.append('<td onclick="rankPageOnCatlogClick(this);"><a class="direct-chat-timestamp">' + json.data[curIndex++] + '</a></td>');
                            if (curIndex >= totalCount) break;
                        }
                    }
                } else {

                }
            }
        }
    );
});